package com.googlecode.monitoria.server;

import java.util.HashMap;
import java.util.Map;

import com.googlecode.monitoria.client.beans.User;

/**
 * Class to manage user sessions.
 * 
 * @author Ricardo Ara&uacute;jo Santos - ricardo@lsd.ufcg.edu.br
 */
public class UserSessionManager {
	
	/**
	 * Simple SessionIDgenerator. It generates the same session ID to the same user
	 * every time.
	 * @author Ricardo Ara&uacute;jo Santos - ricardo@lsd.ufcg.edu.br
	 */
	private static class SessionIDGenerator{

		/**
		 * Generates a session ID based on the user's name.
		 * @param name The user's name
		 * @return The session ID.
		 */
		public static Integer generate(String name) {
			return name.hashCode();
		}
	}
	
	private static UserSessionManager instance;
	private Map<Integer,User> sessionMap;
	
	/**
	 * Default private constructor.
	 */
	private UserSessionManager() {
		sessionMap = new HashMap<Integer, User>();
	}
	
	/**
	 * @return The unique instance of this class.
	 */
	public static UserSessionManager getInstance() {
		if (instance == null) {
			instance = new UserSessionManager();
		}
		return instance;
	}

	/**
	 * Opens a new session to this user.
	 * @param user The user to which the new session is being opened. 
	 */
	public Integer openSession(User user) {
		Integer sessionID = SessionIDGenerator.generate(user.getName());
		if(!sessionMap.containsKey(sessionID)){
			sessionMap.put(sessionID, user);
		}
		return sessionID;
	}

	/**
	 * @param sessionID The session ID.
	 * @return A {@link User} corresponding to such session ID ou <code>null</code> to an
	 * invalid session ID.
	 */
	public User getUserForSession(Integer sessionID) {
		return sessionMap.get(sessionID);
	}

	/**
	 * Closes the session corresponding to this session ID.
	 * @param sessionID The session ID.
	 * @return 
	 */
	public User closeSession( Integer sessionID ) {
		return sessionMap.remove( sessionID );
	}
}